//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package project_member_api_serv

import (
	"context"

	"atomgit.com/openlinksaas/api-server/dao"
	"atomgit.com/openlinksaas/api-server/utils"
	"atomgit.com/openlinksaas/proto-gen-go.git/project_member_api"
	"github.com/dchest/uniuri"
)

func (apiImpl *ProjectMemberApiImpl) GenOneTimeToken(ctx context.Context, req *project_member_api.GenOneTimeTokenRequest) (*project_member_api.GenOneTimeTokenResponse, error) {
	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &project_member_api.GenOneTimeTokenResponse{
			Code:   project_member_api.GenOneTimeTokenResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	projectItem, _, roleItem, err := utils.GetProjectMemberRole(ctx, req.ProjectId, sessionItem.UserId)
	if err == utils.ErrNoProject {
		return &project_member_api.GenOneTimeTokenResponse{
			Code:   project_member_api.GenOneTimeTokenResponse_CODE_NO_PROJECT,
			ErrMsg: "项目不存在",
		}, nil
	} else if err == utils.ErrNoRole {
		return &project_member_api.GenOneTimeTokenResponse{
			Code:   project_member_api.GenOneTimeTokenResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	} else if err != nil {
		return nil, err
	}
	if projectItem.Closed {
		return &project_member_api.GenOneTimeTokenResponse{
			Code:   project_member_api.GenOneTimeTokenResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}
	chars := []byte("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
	tokenItem := &dao.K8sTokenDbItem{
		K8sToken:     uniuri.NewLenChars(128, chars),
		ProjectId:    req.ProjectId,
		MemberUserId: sessionItem.UserId,
	}
	if projectItem.OwnerUserId == sessionItem.UserId || roleItem.BasicInfo.Admin {
		tokenItem.Admin = true
	}
	err = dao.CacheDao.SetK8sToken(ctx, tokenItem)
	if err != nil {
		return nil, err
	}
	return &project_member_api.GenOneTimeTokenResponse{
		Code:  project_member_api.GenOneTimeTokenResponse_CODE_OK,
		Token: tokenItem.K8sToken,
	}, nil
}

func (apiImpl *ProjectMemberApiImpl) GetOneTimeToken(ctx context.Context, req *project_member_api.GetOneTimeTokenRequest) (*project_member_api.GetOneTimeTokenResponse, error) {
	tokenItem, ok := dao.CacheDao.GetK8sToken(ctx, req.Token)
	if !ok {
		return &project_member_api.GetOneTimeTokenResponse{
			Code:      project_member_api.GetOneTimeTokenResponse_CODE_NO_TOKEN,
			ErrMsg:    "访问令牌不存在",
			TokenInfo: &project_member_api.OneTimeTokenInfo{},
		}, nil
	}
	dao.CacheDao.RemoveK8sToken(ctx, req.Token)
	return &project_member_api.GetOneTimeTokenResponse{
		Code: project_member_api.GetOneTimeTokenResponse_CODE_OK,
		TokenInfo: &project_member_api.OneTimeTokenInfo{
			ProjectId:    tokenItem.ProjectId,
			MemberUserId: tokenItem.MemberUserId,
			Admin:        tokenItem.Admin,
		},
	}, nil
}
